import { watch } from 'vue';
import { tryOnScopeDispose, unrefElement, useSupported } from './shared';

export function useMutationObserver(target, callback, options = {}) {
  // 观察器的配置（需要观察什么变动）
  // { attributes: true, childList: true, subtree: true };
  const { ...mutationOptions } = options;

  let observer;
  // 检查 window 是否有 MutationObserver 属性
  const isSupported = useSupported(() => window && 'MutationObserver' in window);
  // 清除 observer
  const cleanup = () => {
    if (observer) {
      observer.disconnect();
      observer = null;
    }
  };

  const stopWatch = watch(() => unrefElement(target), (el) => {
    cleanup();
    console.log('注册MutationObserver！');
    if (isSupported.value && window && el) {
      observer = new MutationObserver(callback);
      observer.observe(el, mutationOptions);
    }
  }, { immediate: true });
  // 停止监听
  const stop = () => {
    cleanup();
    stopWatch();
  };
  // 作用域销毁时 停止监听
  tryOnScopeDispose(stop);
  return {
    isSupported,
    stop
  };
}
